const Glucose = require('../models/Glucose');
const BloodPressure = require('../models/BloodPressure');
const Weight = require('../models/Weight');
const User = require('../models/User');
const { successResponse, errorResponse } = require('../utils/responses');
const asyncHandler = require('express-async-handler');
const RiskAssessment = require('../models/RiskAssessment');

/**
 * @desc    获取用户血糖记录
 * @route   GET /api/health/glucose
 * @access  私有
 */
const getGlucoseRecords = async (req, res) => {
  try {
    const { startDate, endDate, limit = 100, page = 1, category } = req.query;
    const skip = (page - 1) * limit;
    
    // 构建查询条件
    const query = { user: req.user.id };
    
    // 添加日期范围条件
    if (startDate || endDate) {
      query.measuredAt = {};
      if (startDate) {
        query.measuredAt.$gte = new Date(startDate);
      }
      if (endDate) {
        // 设置结束日期为当天的结束时间
        const endDateTime = new Date(endDate);
        endDateTime.setHours(23, 59, 59, 999);
        query.measuredAt.$lte = endDateTime;
      }
    }
    
    // 添加分类条件
    if (category) {
      query.category = category;
    }
    
    // 获取记录总数
    const total = await Glucose.countDocuments(query);
    
    // 获取数据记录
    const records = await Glucose.find(query)
      .sort({ measuredAt: -1 })
      .skip(skip)
      .limit(Number(limit));
    
    return successResponse(res, 200, '获取血糖记录成功', {
      records,
      pagination: {
        total,
        page: Number(page),
        limit: Number(limit),
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error(error);
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    添加血糖记录
 * @route   POST /api/health/glucose
 * @access  私有
 */
const addGlucoseRecord = async (req, res) => {
  try {
    const { value, unit, measuredAt, category, notes, tags, isManualEntry, deviceInfo } = req.body;
    
    // 创建新记录
    const newRecord = new Glucose({
      user: req.user.id,
      value,
      unit: unit || 'mmol/L',
      measuredAt: measuredAt || new Date(),
      category,
      notes,
      tags,
      isManualEntry: isManualEntry !== undefined ? isManualEntry : true,
      deviceInfo
    });
    
    // 保存记录
    const savedRecord = await newRecord.save();
    
    return successResponse(res, 201, '血糖记录添加成功', savedRecord);
  } catch (error) {
    console.error(error);
    
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(val => val.message);
      return errorResponse(res, 400, '验证错误', messages);
    }
    
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    获取单条血糖记录
 * @route   GET /api/health/glucose/:id
 * @access  私有
 */
const getGlucoseRecord = async (req, res) => {
  try {
    const record = await Glucose.findById(req.params.id);
    
    // 检查记录是否存在
    if (!record) {
      return errorResponse(res, 404, '记录未找到');
    }
    
    // 检查记录归属权
    if (record.user.toString() !== req.user.id) {
      return errorResponse(res, 403, '无权访问此记录');
    }
    
    return successResponse(res, 200, '获取血糖记录成功', record);
  } catch (error) {
    console.error(error);
    
    if (error.kind === 'ObjectId') {
      return errorResponse(res, 404, '记录未找到');
    }
    
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    更新血糖记录
 * @route   PUT /api/health/glucose/:id
 * @access  私有
 */
const updateGlucoseRecord = async (req, res) => {
  try {
    let record = await Glucose.findById(req.params.id);
    
    // 检查记录是否存在
    if (!record) {
      return errorResponse(res, 404, '记录未找到');
    }
    
    // 检查记录归属权
    if (record.user.toString() !== req.user.id) {
      return errorResponse(res, 403, '无权修改此记录');
    }
    
    // 更新记录
    const { value, unit, measuredAt, category, notes, tags } = req.body;
    
    if (value !== undefined) record.value = value;
    if (unit !== undefined) record.unit = unit;
    if (measuredAt !== undefined) record.measuredAt = measuredAt;
    if (category !== undefined) record.category = category;
    if (notes !== undefined) record.notes = notes;
    if (tags !== undefined) record.tags = tags;
    
    // 保存更新
    const updatedRecord = await record.save();
    
    return successResponse(res, 200, '血糖记录更新成功', updatedRecord);
  } catch (error) {
    console.error(error);
    
    if (error.kind === 'ObjectId') {
      return errorResponse(res, 404, '记录未找到');
    }
    
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(val => val.message);
      return errorResponse(res, 400, '验证错误', messages);
    }
    
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    删除血糖记录
 * @route   DELETE /api/health/glucose/:id
 * @access  私有
 */
const deleteGlucoseRecord = asyncHandler(async (req, res) => {
  const { id } = req.params;
  const user = req.user._id;

  try {
    // 查找记录
    const record = await Glucose.findOne({ _id: id, user });

    if (!record) {
      return res.status(404).json({
        success: false,
        message: '未找到血糖记录',
        errors: ['记录不存在或已被删除']
      });
    }

    // 删除记录 - 使用deleteOne替代旧的remove方法
    await Glucose.deleteOne({ _id: id });

    res.status(200).json({
      success: true,
      message: '血糖记录删除成功',
      data: { id }
    });
  } catch (error) {
    console.error('删除血糖记录时出错:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误',
      errors: [error.message]
    });
  }
});

/**
 * @desc    获取血糖统计数据
 * @route   GET /api/health/glucose/stats
 * @access  私有
 */
const getGlucoseStats = async (req, res) => {
  try {
    const { startDate, endDate } = req.query;
    
    // 构建查询条件
    const query = { user: req.user.id };
    
    // 添加日期范围条件
    if (startDate || endDate) {
      query.measuredAt = {};
      if (startDate) {
        query.measuredAt.$gte = new Date(startDate);
      }
      if (endDate) {
        // 设置结束日期为当天的结束时间
        const endDateTime = new Date(endDate);
        endDateTime.setHours(23, 59, 59, 999);
        query.measuredAt.$lte = endDateTime;
      }
    }
    
    // 聚合查询获取统计数据
    const stats = await Glucose.aggregate([
      { $match: query },
      { 
        $group: {
          _id: null,
          average: { $avg: '$value' },
          min: { $min: '$value' },
          max: { $max: '$value' },
          count: { $sum: 1 },
          abnormalCount: {
            $sum: { $cond: [{ $eq: ['$abnormal', true] }, 1, 0] }
          }
        }
      }
    ]);
    
    // 按类别统计
    const categoryStats = await Glucose.aggregate([
      { $match: query },
      { 
        $group: {
          _id: '$category',
          average: { $avg: '$value' },
          min: { $min: '$value' },
          max: { $max: '$value' },
          count: { $sum: 1 }
        }
      }
    ]);
    
    // 按时间段分组
    const timeGrouping = await Glucose.aggregate([
      { $match: query },
      {
        $project: {
          value: 1,
          hour: { $hour: '$measuredAt' }
        }
      },
      {
        $group: {
          _id: {
            timeSlot: { 
              $switch: {
                branches: [
                  { case: { $lt: ['$hour', 6] }, then: '凌晨' },
                  { case: { $lt: ['$hour', 12] }, then: '上午' },
                  { case: { $lt: ['$hour', 18] }, then: '下午' },
                  { case: { $gte: ['$hour', 18] }, then: '晚上' }
                ],
                default: '其他'
              }
            }
          },
          average: { $avg: '$value' },
          count: { $sum: 1 }
        }
      }
    ]);
    
    // 按日期分组，计算每日平均值
    const dailyStats = await Glucose.aggregate([
      { $match: query },
      {
        $project: {
          value: 1,
          date: {
            $dateToString: { format: '%Y-%m-%d', date: '$measuredAt' }
          }
        }
      },
      {
        $group: {
          _id: '$date',
          average: { $avg: '$value' },
          min: { $min: '$value' },
          max: { $max: '$value' },
          count: { $sum: 1 }
        }
      },
      { $sort: { _id: 1 } }
    ]);
    
    return successResponse(res, 200, '获取血糖统计数据成功', {
      overall: stats[0] || { average: 0, min: 0, max: 0, count: 0, abnormalCount: 0 },
      byCategory: categoryStats,
      byTimeOfDay: timeGrouping,
      byDate: dailyStats
    });
  } catch (error) {
    console.error(error);
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

// 血压相关控制器
/**
 * @desc    获取用户血压记录
 * @route   GET /api/health/blood-pressure
 * @access  私有
 */
const getBloodPressureRecords = async (req, res) => {
  try {
    const { startDate, endDate, limit = 100, page = 1 } = req.query;
    const skip = (page - 1) * limit;
    
    // 构建查询条件
    const query = { user: req.user.id };
    
    // 添加日期范围条件
    if (startDate || endDate) {
      query.measuredAt = {};
      if (startDate) {
        query.measuredAt.$gte = new Date(startDate);
      }
      if (endDate) {
        // 设置结束日期为当天的结束时间
        const endDateTime = new Date(endDate);
        endDateTime.setHours(23, 59, 59, 999);
        query.measuredAt.$lte = endDateTime;
      }
    }
    
    // 获取记录总数
    const total = await BloodPressure.countDocuments(query);
    
    // 获取数据记录
    const records = await BloodPressure.find(query)
      .sort({ measuredAt: -1 })
      .skip(skip)
      .limit(Number(limit));
    
    return successResponse(res, 200, '获取血压记录成功', {
      records,
      pagination: {
        total,
        page: Number(page),
        limit: Number(limit),
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error(error);
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    添加血压记录
 * @route   POST /api/health/blood-pressure
 * @access  私有
 */
const addBloodPressureRecord = async (req, res) => {
  try {
    const { 
      systolic, diastolic, pulse, measuredAt, 
      measuredArm, bodyPosition, notes, tags, 
      isManualEntry, deviceInfo 
    } = req.body;
    
    // 创建新记录
    const newRecord = new BloodPressure({
      user: req.user.id,
      systolic,
      diastolic,
      pulse,
      measuredAt: measuredAt || new Date(),
      measuredArm,
      bodyPosition,
      notes,
      tags,
      isManualEntry: isManualEntry !== undefined ? isManualEntry : true,
      deviceInfo
    });
    
    // 保存记录
    const savedRecord = await newRecord.save();
    
    return successResponse(res, 201, '血压记录添加成功', savedRecord);
  } catch (error) {
    console.error(error);
    
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(val => val.message);
      return errorResponse(res, 400, '验证错误', messages);
    }
    
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    获取单条血压记录
 * @route   GET /api/health/blood-pressure/:id
 * @access  私有
 */
const getBloodPressureRecord = async (req, res) => {
  try {
    const record = await BloodPressure.findById(req.params.id);
    
    // 检查记录是否存在
    if (!record) {
      return errorResponse(res, 404, '记录未找到');
    }
    
    // 检查记录归属权
    if (record.user.toString() !== req.user.id) {
      return errorResponse(res, 403, '无权访问此记录');
    }
    
    return successResponse(res, 200, '获取血压记录成功', record);
  } catch (error) {
    console.error(error);
    
    if (error.kind === 'ObjectId') {
      return errorResponse(res, 404, '记录未找到');
    }
    
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    更新血压记录
 * @route   PUT /api/health/blood-pressure/:id
 * @access  私有
 */
const updateBloodPressureRecord = async (req, res) => {
  try {
    let record = await BloodPressure.findById(req.params.id);
    
    // 检查记录是否存在
    if (!record) {
      return errorResponse(res, 404, '记录未找到');
    }
    
    // 检查记录归属权
    if (record.user.toString() !== req.user.id) {
      return errorResponse(res, 403, '无权修改此记录');
    }
    
    // 更新记录字段
    const { 
      systolic, diastolic, pulse, measuredAt,
      measuredArm, bodyPosition, notes, tags
    } = req.body;
    
    if (systolic !== undefined) record.systolic = systolic;
    if (diastolic !== undefined) record.diastolic = diastolic;
    if (pulse !== undefined) record.pulse = pulse;
    if (measuredAt !== undefined) record.measuredAt = measuredAt;
    if (measuredArm !== undefined) record.measuredArm = measuredArm;
    if (bodyPosition !== undefined) record.bodyPosition = bodyPosition;
    if (notes !== undefined) record.notes = notes;
    if (tags !== undefined) record.tags = tags;
    
    // 保存更新
    const updatedRecord = await record.save();
    
    return successResponse(res, 200, '血压记录更新成功', updatedRecord);
  } catch (error) {
    console.error(error);
    
    if (error.kind === 'ObjectId') {
      return errorResponse(res, 404, '记录未找到');
    }
    
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(val => val.message);
      return errorResponse(res, 400, '验证错误', messages);
    }
    
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    删除血压记录
 * @route   DELETE /api/health/blood-pressure/:id
 * @access  私有
 */
const deleteBloodPressureRecord = asyncHandler(async (req, res) => {
  const { id } = req.params;
  const user = req.user._id;

  try {
    // 查找记录
    const record = await BloodPressure.findOne({ _id: id, user });

    if (!record) {
      return res.status(404).json({
        success: false,
        message: '未找到血压记录',
        errors: ['记录不存在或已被删除']
      });
    }

    // 删除记录 - 使用deleteOne替代旧的remove方法
    await BloodPressure.deleteOne({ _id: id });

    res.status(200).json({
      success: true,
      message: '血压记录删除成功',
      data: { id }
    });
  } catch (error) {
    console.error('删除血压记录时出错:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误',
      errors: [error.message]
    });
  }
});

// 体重相关控制器
/**
 * @desc    获取用户体重记录
 * @route   GET /api/health/weight
 * @access  私有
 */
const getWeightRecords = async (req, res) => {
  try {
    const { startDate, endDate, limit = 100, page = 1 } = req.query;
    const skip = (page - 1) * limit;
    
    // 构建查询条件
    const query = { user: req.user.id };
    
    // 添加日期范围条件
    if (startDate || endDate) {
      query.measuredAt = {};
      if (startDate) {
        query.measuredAt.$gte = new Date(startDate);
      }
      if (endDate) {
        // 设置结束日期为当天的结束时间
        const endDateTime = new Date(endDate);
        endDateTime.setHours(23, 59, 59, 999);
        query.measuredAt.$lte = endDateTime;
      }
    }
    
    // 获取记录总数
    const total = await Weight.countDocuments(query);
    
    // 获取数据记录
    const records = await Weight.find(query)
      .sort({ measuredAt: -1 })
      .skip(skip)
      .limit(Number(limit));
    
    return successResponse(res, 200, '获取体重记录成功', {
      records,
      pagination: {
        total,
        page: Number(page),
        limit: Number(limit),
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error(error);
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    添加体重记录
 * @route   POST /api/health/weight
 * @access  私有
 */
const addWeightRecord = async (req, res) => {
  try {
    const { 
      value, unit, measuredAt, bodyFatPercentage,
      muscleMass, waterPercentage, notes, tags,
      isManualEntry, deviceInfo 
    } = req.body;
    
    // 创建新记录
    const newRecord = new Weight({
      user: req.user.id,
      value,
      unit: unit || 'kg',
      measuredAt: measuredAt || new Date(),
      bodyFatPercentage,
      muscleMass,
      waterPercentage,
      notes,
      tags,
      isManualEntry: isManualEntry !== undefined ? isManualEntry : true,
      deviceInfo
    });
    
    // 获取用户信息以计算BMI
    const user = await User.findById(req.user.id);
    if (user && user.height) {
      await newRecord.calculateBMI(user.height);
    }
    
    // 保存记录
    const savedRecord = await newRecord.save();
    
    // 如果是最新记录，更新用户当前体重
    if (!measuredAt || new Date(measuredAt) >= new Date(Date.now() - 24 * 60 * 60 * 1000)) {
      user.weight = savedRecord.value;
      if (savedRecord.bmi) {
        user.bmi = savedRecord.bmi;
      }
      await user.save();
    }
    
    return successResponse(res, 201, '体重记录添加成功', savedRecord);
  } catch (error) {
    console.error(error);
    
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(val => val.message);
      return errorResponse(res, 400, '验证错误', messages);
    }
    
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    获取单条体重记录
 * @route   GET /api/health/weight/:id
 * @access  私有
 */
const getWeightRecord = async (req, res) => {
  try {
    const record = await Weight.findById(req.params.id);
    
    // 检查记录是否存在
    if (!record) {
      return errorResponse(res, 404, '记录未找到');
    }
    
    // 检查记录归属权
    if (record.user.toString() !== req.user.id) {
      return errorResponse(res, 403, '无权访问此记录');
    }
    
    return successResponse(res, 200, '获取体重记录成功', record);
  } catch (error) {
    console.error(error);
    
    if (error.kind === 'ObjectId') {
      return errorResponse(res, 404, '记录未找到');
    }
    
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    更新体重记录
 * @route   PUT /api/health/weight/:id
 * @access  私有
 */
const updateWeightRecord = async (req, res) => {
  try {
    let record = await Weight.findById(req.params.id);
    
    // 检查记录是否存在
    if (!record) {
      return errorResponse(res, 404, '记录未找到');
    }
    
    // 检查记录归属权
    if (record.user.toString() !== req.user.id) {
      return errorResponse(res, 403, '无权修改此记录');
    }
    
    // 更新记录字段
    const { 
      value, unit, measuredAt, bodyFatPercentage,
      muscleMass, waterPercentage, notes, tags
    } = req.body;
    
    if (value !== undefined) record.value = value;
    if (unit !== undefined) record.unit = unit;
    if (measuredAt !== undefined) record.measuredAt = measuredAt;
    if (bodyFatPercentage !== undefined) record.bodyFatPercentage = bodyFatPercentage;
    if (muscleMass !== undefined) record.muscleMass = muscleMass;
    if (waterPercentage !== undefined) record.waterPercentage = waterPercentage;
    if (notes !== undefined) record.notes = notes;
    if (tags !== undefined) record.tags = tags;
    
    // 如果体重值或单位改变，重新计算BMI
    if ((value !== undefined || unit !== undefined) && req.user.height) {
      const user = await User.findById(req.user.id);
      await record.calculateBMI(user.height);
    }
    
    // 保存更新
    const updatedRecord = await record.save();
    
    return successResponse(res, 200, '体重记录更新成功', updatedRecord);
  } catch (error) {
    console.error(error);
    
    if (error.kind === 'ObjectId') {
      return errorResponse(res, 404, '记录未找到');
    }
    
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(val => val.message);
      return errorResponse(res, 400, '验证错误', messages);
    }
    
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    删除体重记录
 * @route   DELETE /api/health/weight/:id
 * @access  私有
 */
const deleteWeightRecord = asyncHandler(async (req, res) => {
  const { id } = req.params;
  const user = req.user._id;

  try {
    // 查找记录
    const record = await Weight.findOne({ _id: id, user });

    if (!record) {
      return res.status(404).json({
        success: false,
        message: '未找到体重记录',
        errors: ['记录不存在或已被删除']
      });
    }

    // 删除记录 - 使用deleteOne替代旧的remove方法
    await Weight.deleteOne({ _id: id });

    res.status(200).json({
      success: true,
      message: '体重记录删除成功',
      data: { id }
    });
  } catch (error) {
    console.error('删除体重记录时出错:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误',
      errors: [error.message]
    });
  }
});

/**
 * @desc    获取用户风险评估记录
 * @route   GET /api/health/risk-assessment
 * @access  私有
 */
const getRiskAssessments = async (req, res) => {
  try {
    const { startDate, endDate, limit = 100, page = 1 } = req.query;
    const skip = (page - 1) * limit;
    
    // 构建查询条件
    const query = { user: req.user.id };
    
    // 添加日期范围条件
    if (startDate || endDate) {
      query.measuredAt = {};
      if (startDate) {
        query.measuredAt.$gte = new Date(startDate);
      }
      if (endDate) {
        // 设置结束日期为当天的结束时间
        const endDateTime = new Date(endDate);
        endDateTime.setHours(23, 59, 59, 999);
        query.measuredAt.$lte = endDateTime;
      }
    }
    
    // 获取记录总数
    const total = await RiskAssessment.countDocuments(query);
    
    // 获取数据记录
    const records = await RiskAssessment.find(query)
      .sort({ measuredAt: -1 })
      .skip(skip)
      .limit(Number(limit));
    
    return successResponse(res, 200, '获取风险评估记录成功', {
      records,
      pagination: {
        total,
        page: Number(page),
        limit: Number(limit),
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error(error);
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    添加风险评估记录
 * @route   POST /api/health/risk-assessment
 * @access  私有
 */
const addRiskAssessment = async (req, res) => {
  try {
    const { result, inputData, measuredAt, notes } = req.body;
    
    // 创建新记录
    const newRecord = new RiskAssessment({
      user: req.user.id,
      result,
      inputData,
      measuredAt: measuredAt || new Date(),
      notes
    });
    
    // 保存记录
    const savedRecord = await newRecord.save();
    
    return successResponse(res, 201, '风险评估记录添加成功', savedRecord);
  } catch (error) {
    console.error(error);
    
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(val => val.message);
      return errorResponse(res, 400, '验证错误', messages);
    }
    
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    获取单条风险评估记录
 * @route   GET /api/health/risk-assessment/:id
 * @access  私有
 */
const getRiskAssessment = async (req, res) => {
  try {
    const record = await RiskAssessment.findById(req.params.id);
    
    // 检查记录是否存在
    if (!record) {
      return errorResponse(res, 404, '记录未找到');
    }
    
    // 检查记录归属权
    if (record.user.toString() !== req.user.id) {
      return errorResponse(res, 403, '无权访问此记录');
    }
    
    return successResponse(res, 200, '获取风险评估记录成功', record);
  } catch (error) {
    console.error(error);
    
    if (error.kind === 'ObjectId') {
      return errorResponse(res, 404, '记录未找到');
    }
    
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    删除风险评估记录
 * @route   DELETE /api/health/risk-assessment/:id
 * @access  私有
 */
const deleteRiskAssessment = asyncHandler(async (req, res) => {
  const { id } = req.params;
  const user = req.user._id;

  try {
    // 查找记录
    const record = await RiskAssessment.findOne({ _id: id, user });

    if (!record) {
      return res.status(404).json({
        success: false,
        message: '未找到风险评估记录',
        errors: ['记录不存在或已被删除']
      });
    }

    // 删除记录
    await RiskAssessment.deleteOne({ _id: id });

    res.status(200).json({
      success: true,
      message: '风险评估记录删除成功',
      data: { id }
    });
  } catch (error) {
    console.error('删除风险评估记录时出错:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误',
      errors: [error.message]
    });
  }
});

/**
 * @desc    获取风险评估统计数据
 * @route   GET /api/health/risk-assessment/stats
 * @access  私有
 */
const getRiskAssessmentStats = async (req, res) => {
  try {
    const { days = 90 } = req.query;
    
    // 计算开始日期（默认90天前）
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - Number(days));
    
    // 查询条件
    const query = { 
      user: req.user.id,
      measuredAt: { $gte: startDate }
    };
    
    // 获取记录按时间排序
    const records = await RiskAssessment.find(query)
      .sort({ measuredAt: 1 })
      .select('result measuredAt');
    
    // 计算风险趋势
    let trend = 'stable';
    if (records.length >= 2) {
      const firstRecord = records[0];
      const lastRecord = records[records.length - 1];
      
      // 比较第一条和最后一条记录的风险概率
      if (lastRecord.result.probability < firstRecord.result.probability - 0.05) {
        trend = 'decreasing'; // 风险下降
      } else if (lastRecord.result.probability > firstRecord.result.probability + 0.05) {
        trend = 'increasing'; // 风险上升
      }
    }
    
    // 计算风险等级分布
    const riskLevelDistribution = {
      '低风险': 0,
      '中风险': 0,
      '高风险': 0
    };
    
    records.forEach(record => {
      riskLevelDistribution[record.result.riskLevel]++;
    });
    
    return successResponse(res, 200, '获取风险评估统计数据成功', {
      totalAssessments: records.length,
      trend,
      riskLevelDistribution,
      latestAssessment: records.length > 0 ? records[records.length - 1] : null
    });
  } catch (error) {
    console.error(error);
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

module.exports = {
  // 血糖相关
  getGlucoseRecords,
  addGlucoseRecord,
  getGlucoseRecord,
  updateGlucoseRecord,
  deleteGlucoseRecord,
  getGlucoseStats,
  
  // 血压相关
  getBloodPressureRecords,
  addBloodPressureRecord,
  getBloodPressureRecord,
  updateBloodPressureRecord,
  deleteBloodPressureRecord,
  
  // 体重相关
  getWeightRecords,
  addWeightRecord,
  getWeightRecord,
  updateWeightRecord,
  deleteWeightRecord,
  
  // 新增导出
  getRiskAssessments,
  addRiskAssessment,
  getRiskAssessment,
  deleteRiskAssessment,
  getRiskAssessmentStats
}; 